package server;

import requestEnvelopes.agent.ReceiveEvent;
import server.interfaces.IMobileAgentExecutionEngine;

import com.Event;
import com.LedsManager;
import com.sun.spot.interisolate.ReplyEnvelope;
import com.sun.spot.interisolate.RequestSender;
import com.sun.squawk.io.mailboxes.NoSuchMailboxException;

public class TerminateAgentThread extends Thread {
	
	private String agentName;
	
	private IMobileAgentExecutionEngine executionEngine;
	
	public TerminateAgentThread (IMobileAgentExecutionEngine executionEngine, String agentName) {
		this.agentName = agentName;
		this.executionEngine = executionEngine;
	}
	
	public void run(){
		try {
			
			RequestSender agent	= RequestSender.lookup(agentName);
			Event eventTerminateAgent = new Event(this.executionEngine.getExecutionEngineName(), agentName, 
					Event.AGN_TERMINATED, Event.NOW);
			ReplyEnvelope reply = agent.send(new ReceiveEvent(eventTerminateAgent));
			reply.checkForRuntimeException();			
			this.executionEngine.removeAgent(agentName);
		}
		catch (NoSuchMailboxException e) {
			LedsManager.error();
			e.printStackTrace();
		}
	}
	
}
